package com.yangcangclub.pay.tenpay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Component
public class WeChatHttpClient {
	public static String sendMsg(String sendStr, String partner, String file) throws Exception{
	
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
	    FileInputStream instream = new FileInputStream(new File(file));
	    try {
	        keyStore.load(instream, partner.toCharArray());
	    } finally {
	        instream.close();
	    }
	
	    // Trust own CA and all self-signed certs
	    SSLContext sslcontext = SSLContexts.custom()
	            .loadKeyMaterial(keyStore, partner.toCharArray())
	            .build();
	    // Allow TLSv1 protocol only
	    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	            sslcontext,
	            new String[] { "TLSv1" },
	            null,
	            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	    CloseableHttpClient httpclient = HttpClients.custom()
	            .setSSLSocketFactory(sslsf)
	            .build();
	    try {
	
	        HttpPost post = new HttpPost(WeChatConfig.REFUND_URL);
	        StringEntity postEntity = new StringEntity(sendStr, "UTF-8");
	        post.setEntity(postEntity);
	
	        CloseableHttpResponse response = httpclient.execute(post);
	        try {
	        	HttpEntity entity = response.getEntity();
	        	String result = "";
	            if (entity != null) {
	                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
	                String text = ""; 
	                while ((text = bufferedReader.readLine()) != null) {
	                	result += text;
	                }
	               return result;
	            }
	            EntityUtils.consume(entity);
	        } finally {
	            response.close();
	        }
	    } finally {
	    	httpclient.close();
	    }
	    return null;
	}
}
